import React, { Component } from 'react'
import { nanoid } from 'nanoid'
import List from './components/List'
import Header from './components/Header'
import Footer from './components/Footer'
import './App.css'
class App extends Component {
  // 初始化数据
  state = {
    todos: [
      { id: 1, name: '吃饭', done: true },
      { id: 2, name: '睡觉', done: true },
      { id: 3, name: '打代码', done: false },
      { id: 4, name: '写代码', done: false }
    ],
    allNumber: 4,
    selectNumber: 2
  }

  // 勾选框变化
  onChange = (id, done) => {
    const { todos, selectNumber } = this.state
    // 用forEach加工数据
    // const newTodos = []
    // todos.forEach(w => {
    //    if (w.id === id) {
    //     w.done = done
    //    }
    //    newTodos.push({...w})
    // });
    // this.setState({todos: newTodos})

    // 用map加工数据
    const newTodos = todos.map(w => {
      if (w.id === id) return { ...w, done }
      else return w
    });
    this.setState({ todos: newTodos })
    if (done) {
      this.setState({ selectNumber: selectNumber + 1 })
    } else {
      this.setState({ selectNumber: selectNumber - 1 })
    }
  }

  // 添加
  addItem = (name) => {
    const { todos, allNumber } = this.state
    const newTodos = [{
      id: nanoid(),
      name,
      done: false,
    }, ...todos]
    this.setState({ todos: newTodos })
    this.setState({ allNumber: allNumber + 1 })
  }
  // 删除
  deleteItem = (id) => {
    const { todos } = this.state
    // 用splice删除数据
    // const index = todos.findIndex(w => w.id === id)
    // todos.splice(index, 1)
    // this.setState({ todos: todos })
    // this.setState({ selectNumber: todos.filter(w => w.done).length })
    // this.setState({ allNumber: todos.length })
    // 用filter删除数据
    const newTodos = todos.filter(w => w.id !== id)
    this.setState({ todos: newTodos })
    this.setState({ selectNumber: newTodos.filter(w => w.done).length })
    this.setState({ allNumber: newTodos.length })
  }

  // 删除
  deleteCheck = () => {
    // 用forEach
    // const newTodos = []
    // this.state.todos.forEach(w => {
    //   if (!w.done) {
    //     newTodos.push({ ...w })
    //   }
    // });
    // 用filter删除数据
    const newTodos = this.state.todos.filter(w => !w.done)
    this.setState({ todos: newTodos })
    this.setState({ selectNumber: newTodos.filter(w => w.done).length })
    this.setState({ allNumber: newTodos.length })
  }
  checkAll = (done) => {
    const { todos } = this.state
    const newTodos = todos.map(w => {
      return { ...w, done }
    });
    this.setState({ todos: newTodos })
  }
  render() {
    const { todos } = this.state
    return (
      <div className='APP-ALL'>
        <Header addItem={this.addItem} />
        <List todos={todos} onChange={this.onChange} deleteItem={this.deleteItem} />
        <Footer todos={todos} deleteCheck={this.deleteCheck} checkAll={this.checkAll} />
      </div>
    )
  }
}

// 对外暴露APP
export default App;